import os
import subprocess
from easydict import EasyDict as edict
import logging
import datetime
import time
from pathlib import Path

def record_rtsp(rtsp_addr, out_file):
    cmd = ['ffmpeg', '-t', str(args.duration),  '-i', rtsp_addr, '-vcodec', 'copy', '-y', out_file]
    logging.debug(f"record cmd: {' '.join(cmd)}")
    ret = subprocess.run(
        cmd,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT
    )
    if ret.returncode:
        logging.info('recoding fails')
        # print(ret.stderr)
    else:
        logging.info('recording success')

def set_logger(log_file):
    logging.basicConfig(
        level=logging.DEBUG,
        format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
        datefmt='%a, %d %b %Y %H:%M:%S',
        filename=log_file,
        filemode='w'
    )

def check_now_valid(args):
    now = datetime.datetime.now()
    s = datetime.datetime(now.year, now.month, now.day, args.start_time.hour, args.start_time.minute)
    e = datetime.datetime(now.year, now.month, now.day, args.end_time.hour, args.end_time.minute)
    return now > s and now < e            

if __name__ == '__main__':
    args = edict()
    args.root = '../data'
    args.rtsp_addr = 'rtsp://192.168.8.151:554/live/1/1'
    args.interval = 300                                     # time interval between two recording
    args.duration = 60                                      # each recording's duration
    args.start_time = datetime.time(hour=8, minute=30)      # every day's start time
    args.end_time = datetime.time(hour=18, minute=30)       # every day's end time
    args.log_file = './log.txt'

    set_logger(args.log_file)

    logging.info(f'current time: {datetime.datetime.now()}, starting collect data')
    logging.info(f'args: {args}')

    tic = 0
    while True:
        if not check_now_valid(args):
            time.sleep(5)
            continue
        toc = time.time()
        if toc - tic > args.interval:
            tic = toc
            out_file = Path(args.root) / time.strftime('%Y_%m_%d') / (time.strftime('%H_%M_%S')+'.mp4')
            out_file.parent.mkdir(parents=True, exist_ok=True)
            logging.info(f'recording into {out_file}')
            record_rtsp(args.rtsp_addr, str(out_file))
